package com.xinling.modules.user.service.impl;

import com.xinling.modules.user.mapper.UserMapper;
import com.xinling.modules.user.model.dto.LoginDTO;
import com.xinling.modules.user.model.dto.RegisterDTO;
import com.xinling.modules.user.model.entity.User;
import com.xinling.modules.user.model.vo.UserVO;
import com.xinling.modules.user.service.UserService;
import com.xinling.security.util.JwtTokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public UserVO register(RegisterDTO registerDTO) {
        if (userMapper.findByUsername(registerDTO.getUsername()) != null) {
            return null; // 用户名已存在
        }
        if (userMapper.findByEmail(registerDTO.getEmail()) != null) {
            return null; // 邮箱已注册
        }
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setEmail(registerDTO.getEmail());
        user.setRole("user");
        user.setAvatar("default-avatar.png");
        userMapper.insert(user);
        return convertToVO(user);
    }

    @Override
    public String login(LoginDTO loginDTO) {
        User user = userMapper.findByUsername(loginDTO.getUsername());
        if (user == null) {
            return "-1"; // 用户不存在
        }
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            return "-2"; // 密码错误
        }
        // 生成JWT token（subject为username）
        return jwtTokenUtil.generateToken(
            new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                Collections.emptyList()
            )
        );
    }

    @Override
    public UserVO getCurrentUser() {
        String username = getUsernameFromToken();
        if (username == null) return null;
        User user = userMapper.findByUsername(username);
        if (user == null) return null;
        return convertToVO(user);
    }

    @Override
    public UserVO updateUserInfo(UserVO userVO) {
        String username = getUsernameFromToken();
        if (username == null) return null;
        User user = userMapper.findByUsername(username);
        if (user == null) return null;
        user.setUsername(userVO.getUsername());
        user.setEmail(userVO.getEmail());
        user.setAvatar(userVO.getAvatar());
        userMapper.updateUserInfo(user);
        return convertToVO(user);
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword) {
        String username = getUsernameFromToken();
        if (username == null) return;
        User user = userMapper.findByUsername(username);
        if (user == null) return;
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return;
        }
        userMapper.updatePassword(user.getId(), passwordEncoder.encode(newPassword));
    }

    @Override
    public String uploadAvatar(MultipartFile file) {
        // 这里只做演示，实际应保存文件并返回URL
        return "avatar-url";
    }

    private UserVO convertToVO(User user) {
        System.out.println("当前用户=================>"+user);
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user, vo);
        vo.setId(Integer.parseInt(user.getId()+""));
        return vo;
    }

    private String getUsernameFromToken() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) return null;
        HttpServletRequest request = attrs.getRequest();
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) return null;
        return jwtTokenUtil.getUsernameFromToken(token.replace("Bearer ", ""));
    }
} 